package org.summerframework.component.upload;

import org.summerframework.component.upload.exception.UploadFileException;
import org.summerframework.core.util.RandomUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 石超
 * @version v1.0.0
 */
public abstract class AbstractUploadServerService implements FileUploadServerService {

    protected static final byte[] EMPTY_BYTES = new byte[0];

    protected String getPath(String fileName) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MMdd/HHmm/");
        return "/image" + simpleDateFormat.format(new Date()) + RandomUtil.createRandomCode(6, true) + "." + FilenameUtils.getExtension(fileName);
    }

    protected String getPath(String start, String fileName) {
        return FilenameUtils.separatorsToUnix(FilenameUtils.normalize((StringUtils.equalsAny(start, "/", "\\") ? "" : start) + fileName));
    }

    @Override
    public String uploadFile(String path) {
        if (StringUtils.isBlank(path)) {
            return null;
        }
        try {
            return uploadFile(new FileInputStream(new File(path)), FilenameUtils.getName(path));
        } catch (IOException e) {
            throw new UploadFileException(UploadResultCode.ERROR_UPLOAD_FAILURE);
        }
    }

    @Override
    public String uploadFile(byte[] bytes, String fileName) {
        return uploadFile(new ByteArrayInputStream(bytes), fileName);
    }
}
